package com.yu.processor;

import com.yu.ApplicationContext;
import com.yu.annotion.Autowired;
import com.yu.annotion.Component;
import com.yu.annotion.ScopeName;
import com.yu.bean.BeanDefinition;
import com.yu.commoninterface.ApplicationContextAware;
import com.yu.commoninterface.BeanPostProcessor;

import javax.annotation.Resource;

// TODO AOP代理
@Component
public class AspectAutoProxyBeanProcessor implements BeanPostProcessor, ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws Exception {
        this.applicationContext = applicationContext;
    }

    private ApplicationContext applicationContext;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        BeanDefinition beanDefinition = applicationContext.getBeanDefinitionMap().get(beanName);
        // TODO 延迟执行的aop代理 转换成Proxy代理对象(可能在创建其他依赖的时候已经被提前aop代理了)
        if (beanDefinition.getScopeName() == ScopeName.ENUM_singleton) { // 单例模式
            // TODO (已经被提前代理过了)
            if (applicationContext.getEarlySingletonObjects().containsKey(beanDefinition.getBeanName())) {
                bean = applicationContext.getEarlySingletonObjects().remove(beanDefinition.getBeanName()); // 升级到1级缓存
            } else {
                // TODO 没有被提前暴露就执行Aop代理 转换成Proxy代理对象
                bean = applicationContext.wrapperBeanToAopIfNecessary(bean, beanDefinition.getBeanName());
                applicationContext.getSingletonFactories().remove(beanDefinition.getBeanName()); // 删除3级缓存
            }
            applicationContext.getEarlySingletonObjects().put(beanDefinition.getBeanName(), bean);
        } else { // 多例模式
            bean = applicationContext.wrapperBeanToAopIfNecessary(bean, beanDefinition.getBeanName());
        }
        return bean;
    }

}
